package com.hmall.ebiz.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.hmall.ebiz.common.ServerResponse;
import com.hmall.ebiz.mapper.DbConfigDao;
import com.hmall.ebiz.model.DbConfig;
import com.hmall.ebiz.service.DbConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.ebiz.utils.*;
import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Thomas Wang
 * @since 2019-02-21
 */

@Service
public class DbConfigServiceImpl extends ServiceImpl<DbConfigDao, DbConfig> implements DbConfigService {
    private OSSClientUtil ossClient= new OSSClientUtil();

    @Override
    public ServerResponse selectModelById(Integer id, Integer userId) throws Exception {
        DbConfig dbConfig = this.getById(id);
        if (dbConfig != null) {
            return ServerResponse.createBySuccess(dbConfig);
        }
        return ServerResponse.createByErrorMessage("查找失败");
    }

    @Override
    public ServerResponse updateOrAddModel(String jsonModel, boolean type, Integer userId) throws Exception {
//        false是添加
        try {
            Gson gson = new Gson();
            DbConfig dbConfig = gson.fromJson(jsonModel, DbConfig.class);
            if (this.checkParam(dbConfig) != null) {
                return ServerResponse.createByErrorMessage(this.checkParam(dbConfig));
            }
            if (type == false) {
                dbConfig.setId(null);
                boolean isSuccess = this.save(dbConfig);
                return ServerResponse.createResultByBool(isSuccess, "新增成功");
            }else {
                boolean isSuccess = this.updateById(dbConfig);
                return ServerResponse.createResultByBool(isSuccess, "更新成功");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return ServerResponse.createByErrorMessage("json 类型错误");
    }

    @Override
    public ServerResponse searchConfigModel(Integer pageSize, Integer pageIndex, String dbName, Integer userId) throws Exception {
        QueryWrapper<DbConfig> queryWrapper = new QueryWrapper();
        if (dbName != null && !dbName.isEmpty()) {
            queryWrapper.like("db_name", dbName);
        }
        Page page = new Page<DbConfig>(pageIndex, pageSize);
        queryWrapper.orderByDesc("create_time");
        IPage iPage = this.page(page, queryWrapper);
        return ServerResponse.createBySuccess(iPage);
    }

    @Override
    public ServerResponse deleteConfigModel(String dbId, Integer userId) throws Exception {
        try {
            Integer intId = Integer.parseInt(dbId);
            DbConfig dbConfig = this.getById(intId);
            if (dbConfig != null) {
                this.removeById(intId);
                return ServerResponse.createBySuccessMessage("删除成功");
            }
        }catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return ServerResponse.createByErrorCodeMessage(1, "没有找到该数据");
    }

    @Override
    public ServerResponse getTableList(Integer id, Integer userId) throws Exception {
        DbConfig dbConfig = this.getById(id);
        if (dbConfig != null) {
            List<String> list = AutoConnectDatabase.connectionDataBase(dbConfig.getDbDriverName(),dbConfig.getDbUrl(), dbConfig.getDbUsername(),dbConfig.getDbPassword(), dbConfig.getDbName());
            return ServerResponse.createBySuccess(list);
        }
        return ServerResponse.createByErrorMessage("获取信息失败");
    }

    @Override
    public ServerResponse createCodeZip(String jsonArray, Integer userId, Integer dbId) throws Exception {

        DbConfig config = getById(dbId);
        if (config == null) {
            return ServerResponse.createByErrorMessage("dbId 未查到");
        }
        String[] tables = jsonArray.split(",");

//        config.setDbUrl("jdbc:mysql://47.98.169.251:3306/hmall-dev2?characterEncoding=utf-8&useSSL=false");
//        config.setDbUsername("root");
//        config.setDbPassword("welL&Ccome123");
//        config.setActvieRecord(1);
//        config.setDbDriverName("com.mysql.cj.jdbc.Driver");
//        config.setResultMap(1);
       CodeGenerator.generateByTables(config, config.getEntityPackageName(), tables);

        File directory = new File("");// 参数为空
        String courseFile = null;
        try {
            courseFile = directory.getCanonicalPath();
            courseFile = courseFile + "/codeZip/";
            System.out.println(courseFile);
        }catch (Exception e) {

        }
        FileUtil util = new FileUtil(courseFile + "dist.zip", courseFile +"com");
        try {
            util.zip();
        }catch (Exception e) {
            e.printStackTrace();
        }
        File file = new File(courseFile + "dist.zip");

        Map<String, String> map = new HashMap<>();
        map.put("file", courseFile + "dist.zip");
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
            return ServerResponse.createBySuccess(updateHead(multipartFile));
        }catch (Exception e) {
            e.printStackTrace();
        }

        return ServerResponse.createBySuccess("");
    }

    private String updateHead(MultipartFile file) throws Exception {
        if (file == null || file.getSize() <= 0) {
            throw new Exception("文件不能为空");
        }
        String name = ossClient.uploadImg2Oss(file);
        return ossClient.getImgUrl(name);
    }

    private String checkParam(DbConfig dbConfig) {
        System.out.println(StrUtil.isNullOrEmpty(dbConfig.getDbPassword()));
        if (StrUtil.isNullOrEmpty(dbConfig.getDbPassword())
                || StrUtil.isNullOrEmpty(dbConfig.getDbName())
                || StrUtil.isNullOrEmpty(dbConfig.getDbUrl())
                || StrUtil.isNullOrEmpty(dbConfig.getDbDriverName())
                || StrUtil.isNullOrEmpty(dbConfig.getDbUsername())
                ) {
            return "dbPassword、dbDriverName、dbUsername、dbUrl、dbName不能为空";
        } else {
            return null;
        }
    }
}
